package com.ruitaowang.admin.view.api;

import com.ruitaowang.account.security.LYSecurityUtil;
import com.ruitaowang.account.service.SysUserService;
import com.ruitaowang.core.domain.*;
import com.ruitaowang.core.web.BaseController;
import com.ruitaowang.core.web.MsgOut;
import com.ruitaowang.goods.service.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
public class APICollectionController extends BaseController{


    @Autowired
    private CollectionService collectionService;
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private CompanyService companyService;
    @Autowired
    private UserCouponService userCouponService;
    @Autowired
    private CouponService couponService;
    @Autowired
    private SysUserService sysUserService;



    /**
     * @api {get} /api/wap/collection 收藏-查询所有
     * @apiVersion 0.1.0
     * @apiSampleRequest /api/wap/collection
     *
     * @apiName list
     * @apiGroup collection
     *
     * @apiParam {String} remark 备注.
     * @apiParam {long} goodsId 商品ID.
     * @apiParam {long} companyId 商户ID.
     * @apiParam {long} couponId 优惠券 ID.
     *
     * @apiSuccess {int} code 接口返回状态码.
     * @apiSuccess {String} msg  接口返回信息.
     * @apiSuccess {Object} data  接口返回数据.
     *
     * @apiSuccessExample Success-Response:
     *     HTTP/1.1 200 OK
     *
     *    {
     *       "code":0,
     *       "data":[
     *           {
     *                   "ctime":1502870415259,
     *                   "id":8,
     *                   "couponId":0,
     *                   "companyId":0,
     *                   "goodsId":0,
     *                   "mtime":1502870415259,
     *                   "remark":"",
     *                   "userId":6
     *                   "rstatus":0,
     *           }
     *       ],
     *       "msg":"操作成功啦",
     *       "records":5,
     *       "title":"成功",
     *       "total":1,
     *       "type":"SUCCESS"
     *    }
     *
     * @apiError InternalServerError.
     *
     * @apiErrorExample Error-Response:
     *     HTTP/1.1 500 Internal Server Error
     *  {
     *      "timestamp":1504064947603,
     *      "status":500,
     *      "error":"Internal Server Error",
     *      "exception":"java.lang.ArithmeticException",
     *      "message":"/ by zero",
     *      "path":"/api/wap/collection"
     *  }
     */
    @RequestMapping("/api/wap/collection")
    public String list(Collection collection,@RequestHeader(value="headId",required = false) String userId) {
        if (ObjectUtils.isEmpty(userId)){
            return this.renderJson(MsgOut.error("Plz login."));
        }
        SysUser user = sysUserService.selectByPK(Long.parseLong(userId));
        collection.setUserId(user.getId());
        MsgOut o = MsgOut.success(collectionService.select(collection));
        return this.renderJson(o);
    }
    /**
     * @api {get} /api/wap/collection/page 收藏-(分页)查询所有
     * @apiVersion 0.1.0
     * @apiSampleRequest /api/wap/collection/page
     *
     * @apiName listForPage
     * @apiGroup collection
     *
     * @apiParam {int} page 第几页.
     * @apiParam {int} rows 每页条数.
     * @apiParam {String} remark 备注.
     * @apiParam {long} goodsId 商品ID.
     * @apiParam {long} companyId 商户ID.
     * @apiParam {long} couponId 优惠券 ID.
     *
     * @apiSuccess {int} code 接口返回状态码.
     * @apiSuccess {String} msg  接口返回信息.
     * @apiSuccess {Object} data  接口返回数据.
     *
     * @apiSuccessExample Success-Response:
     *     HTTP/1.1 200 OK
     *
     *    {
     *       "code":0,
     *       "data":[
     *           {
     *                   "ctime":1502870415259,
     *                   "id":8,
     *                   "couponId":0,
     *                   "companyId":0,
     *                   "goodsId":0,
     *                   "mtime":1502870415259,
     *                   "remark":"",
     *                   "userId":6
     *                   "rstatus":0,
     *           }
     *       ],
     *       "msg":"操作成功啦",
     *       "records":5,
     *       "title":"成功",
     *       "total":1,
     *       "type":"SUCCESS"
     *    }
     *
     * @apiError InternalServerError.
     *
     * @apiErrorExample Error-Response:
     *     HTTP/1.1 500 Internal Server Error
     *  {
     *      "timestamp":1504064947603,
     *      "status":500,
     *      "error":"Internal Server Error",
     *      "exception":"java.lang.ArithmeticException",
     *      "message":"/ by zero",
     *      "path":"/api/wap/collection/page"
     *  }
     */
    @RequestMapping("/api/wap/collection/page")
    public String listForPage(Collection collection, int page,@RequestHeader(value="headId",required = false) String userId) {
        collection.setPage(page);
        if (!ObjectUtils.isEmpty(collection.getSidx())) {
            collection.setOrderBy(collection.getSidx() + " " + collection.getSord() + "," + collection.getOrderBy());
        }
        if (ObjectUtils.isEmpty(userId)){
            return this.renderJson(MsgOut.error("Plz login."));
        }
        SysUser user = sysUserService.selectByPK(Long.parseLong(userId));
        collection.setUserId(user.getId());
        List listOut=new ArrayList();

        List<Collection> collections=collectionService.selectForPage(collection);
        for (Collection c:collections){
            if (c.getCollectionType() == 1){
                Goods goods=goodsService.selectByPK(c.getGoodsId());
                if (!ObjectUtils.isEmpty(goods)){
                    GoodsVO goodsVO= new GoodsVO();
                    BeanUtils.copyProperties(goods,goodsVO);
                    goodsVO.setCollectionId(c.getId());
                    Coupon coupon=new Coupon();
                    coupon.setCompanyId(goodsVO.getGoodsProviderId());
                    coupon.setGoodsId(goodsVO.getGoodsId());
                    coupon.setCouponType((byte)2);
                    List<Coupon> coupons=couponService.select(coupon);
                    goodsVO.setCouponList(coupons);
                    listOut.add(goodsVO);
                }

            }
            if (c.getCollectionType() == 2){
                Company company=companyService.selectByPK(c.getCompanyId());
                if (!ObjectUtils.isEmpty(company)){
                    CompanyVO companyVO=new CompanyVO();
                    BeanUtils.copyProperties(company,companyVO);
                    companyVO.setCollectionId(c.getId());
                    if (ObjectUtils.isEmpty(company.getHeadimgurl())){
                        companyVO.setHeadimgurl("http://static.ruitaowang.com/attached/file/2018/07/09/20180709155656054.jpg");
                    }
                    listOut.add(companyVO);
                }
            }
            if (c.getCollectionType() == 3){
                UserCouponVO userCouponVO=new UserCouponVO();
                UserCoupon userCoupon=userCouponService.selectByPK(c.getCouponId());
                LOGGER.info("GoodsID的值为：" + userCoupon.getGoodsId());
                if (!ObjectUtils.isEmpty(userCoupon)){
                    BeanUtils.copyProperties(userCoupon,userCouponVO);
                    userCouponVO.setGoodsName(goodsService.selectByPK(userCoupon.getGoodsId()).getGoodsName());
                    listOut.add(userCouponVO);
                }
            }
        }
        MsgOut o = MsgOut.success(listOut);
        o.setRecords(collection.getRecords());
        o.setTotal(collection.getTotal());
        return this.renderJson(o);
    }
    /**
     * @api {post} /api/wap/collection 收藏-创建
     * @apiVersion 0.1.0
     * @apiSampleRequest /api/wap/collection
     *
     * @apiName create
     * @apiGroup collection
     *
     * @apiParam {String} remark 备注.
     * @apiParam {long} goodsId 商品ID.
     * @apiParam {long} companyId 商户ID.
     * @apiParam {long} couponId 优惠券 ID.
     *
     * @apiSuccess {int} code 接口返回状态码.
     * @apiSuccess {String} msg  接口返回信息.
     * @apiSuccess {Object} data  接口返回数据.
     *
     * @apiSuccessExample Success-Response:
     *     HTTP/1.1 200 OK
     *
     *    {
     *       "code":0,
     *       "data":[
     *           {
     *                   "ctime":1502870415259,
     *                   "id":8,
     *                   "couponId":0,
     *                   "companyId":0,
     *                   "goodsId":0,
     *                   "mtime":1502870415259,
     *                   "remark":"",
     *                   "userId":6
     *                   "rstatus":0,
     *           }
     *       ],
     *       "msg":"操作成功啦",
     *       "records":5,
     *       "title":"成功",
     *       "total":1,
     *       "type":"SUCCESS"
     *    }
     *
     * @apiError InternalServerError.
     *
     * @apiErrorExample Error-Response:
     *     HTTP/1.1 500 Internal Server Error
     *  {
     *      "timestamp":1504064947603,
     *      "status":500,
     *      "error":"Internal Server Error",
     *      "exception":"java.lang.ArithmeticException",
     *      "message":"/ by zero",
     *      "path":"/api/wap/collection"
     *  }
     */
    @RequestMapping(value = "/api/wap/collection", method = RequestMethod.POST)
    public String create(Collection collection,@RequestHeader(value="headId",required = false) String userId) {
        if (ObjectUtils.isEmpty(userId)){
            return this.renderJson(MsgOut.error("Plz login."));
        }
        SysUser user = sysUserService.selectByPK(Long.parseLong(userId));
        collection.setUserId(user.getId());
        List<Collection> collections=collectionService.select(collection);
        if (!ObjectUtils.isEmpty(collections)){
            return this.renderJson(MsgOut.error("禁止重复关注"));
        }else {
            collectionService.insert(collection);
        }
        MsgOut o = MsgOut.success(collection);
        return this.renderJson(o);
    }
    /**
     * @api {put} /api/wap/collection 收藏-修改
     * @apiVersion 0.1.0
     * @apiSampleRequest /api/wap/collection
     *
     * @apiName update
     * @apiGroup collection
     *
     * @apiParam {String} remark 备注.
     * @apiParam {long} goodsId 商品ID.
     * @apiParam {long} companyId 商户ID.
     * @apiParam {long} couponId 优惠券 ID.
     *
     * @apiSuccess {int} code 接口返回状态码.
     * @apiSuccess {String} msg  接口返回信息.
     * @apiSuccess {Object} data  接口返回数据.
     *
     * @apiSuccessExample Success-Response:
     *     HTTP/1.1 200 OK
     *
     *    {
     *       "code":0,
     *       "data":[
     *           {
     *                   "ctime":1502870415259,
     *                   "id":8,
     *                   "couponId":0,
     *                   "companyId":0,
     *                   "goodsId":0,
     *                   "mtime":1502870415259,
     *                   "remark":"",
     *                   "userId":6
     *                   "rstatus":0,
     *           }
     *       ],
     *       "msg":"操作成功啦",
     *       "records":5,
     *       "title":"成功",
     *       "total":1,
     *       "type":"SUCCESS"
     *    }
     *
     * @apiError InternalServerError.
     *
     * @apiErrorExample Error-Response:
     *     HTTP/1.1 500 Internal Server Error
     *  {
     *      "timestamp":1504064947603,
     *      "status":500,
     *      "error":"Internal Server Error",
     *      "exception":"java.lang.ArithmeticException",
     *      "message":"/ by zero",
     *      "path":"/api/wap/collection"
     *  }
     */
    @RequestMapping(value = "/api/wap/collection", method = RequestMethod.PUT)
    public String update(Collection collection,@RequestHeader(value="headId",required = false) String userId) {
        if (ObjectUtils.isEmpty(userId)){
            return this.renderJson(MsgOut.error("Plz login."));
        }
        collectionService.update(collection);
        MsgOut o = MsgOut.success(collection);
        return this.renderJson(o);
    }
    /**
     * @api {delete} /api/wap/collection/{id} 收藏-删除
     * @apiVersion 0.1.0
     * @apiSampleRequest /api/wap/collection/{id}
     *
     * @apiName delete
     * @apiGroup collection
     *
     * @apiParam {long} id 评论ID.
     *
     * @apiSuccess {int} code 接口返回状态码.
     * @apiSuccess {String} msg  接口返回信息.
     * @apiSuccess {Object} data  接口返回数据.
     *
     * @apiSuccessExample Success-Response:
     *     HTTP/1.1 200 OK
     *
     *    {
     *       "code":0,
     *       "data":1
     *       "msg":"操作成功啦",
     *       "records":5,
     *       "title":"成功",
     *       "total":1,
     *       "type":"SUCCESS"
     *    }
     *
     * @apiError InternalServerError.
     *
     * @apiErrorExample Error-Response:
     *     HTTP/1.1 500 Internal Server Error
     *  {
     *      "timestamp":1504064947603,
     *      "status":500,
     *      "error":"Internal Server Error",
     *      "exception":"java.lang.ArithmeticException",
     *      "message":"/ by zero",
     *      "path":"/api/wap/collection/{id}"
     *  }
     */
    @RequestMapping(value = "/api/wap/collection/{id}", method = RequestMethod.DELETE)
    public String delete(@PathVariable("id") Long id,@RequestHeader(value="headId",required = false) String userId) {
        if (ObjectUtils.isEmpty(userId)){
            return this.renderJson(MsgOut.error("Plz login."));
        }
        MsgOut o = MsgOut.success(collectionService.delete(id));
        return this.renderJson(o);
    }
    @RequestMapping(value = "/api/wap/collection/delete", method = RequestMethod.POST)
    public String deleteForIds(String id,int type,@RequestHeader(value="headId",required = false) String userId) {
        if (ObjectUtils.isEmpty(userId)){
            return this.renderJson(MsgOut.error("Plz login."));
        }
        if (ObjectUtils.isEmpty(id)) {
            return this.renderJson(MsgOut.error("参数错误"));
        }
        if (type == 1 || type ==2){
            String ids[]=id.split(",");
            for (int i=0;i <ids.length;i++){
                collectionService.delete(Long.parseLong(ids[i]));
            }
        }
        if (type==3){
            String couponTds[]=id.split(",");
            for (int i=0;i <couponTds.length;i++){
                userCouponService.delete(Long.parseLong(couponTds[i]));
            }
        }
        MsgOut o = MsgOut.success(id);
        return this.renderJson(o);
    }
    /**
     * @api {get} /api/wap/collection/{id} 收藏-单个查询
     * @apiVersion 0.1.0
     * @apiSampleRequest /api/wap/collection/{id}
     *
     * @apiName findCommentId
     * @apiGroup collection
     *
     * @apiParam {long} id 评论ID.
     *
     * @apiSuccess {int} code 接口返回状态码.
     * @apiSuccess {String} msg  接口返回信息.
     * @apiSuccess {Object} data  接口返回数据.
     *
     * @apiSuccessExample Success-Response:
     *     HTTP/1.1 200 OK
     *
     *    {
     *       "code":0,
     *       "data":[
     *           {
     *                   "ctime":1502870415259,
     *                   "id":8,
     *                   "couponId":0,
     *                   "companyId":0,
     *                   "goodsId":0,
     *                   "mtime":1502870415259,
     *                   "remark":"",
     *                   "userId":6
     *                   "rstatus":0,
     *           }
     *       ],
     *       "msg":"操作成功啦",
     *       "records":5,
     *       "title":"成功",
     *       "total":1,
     *       "type":"SUCCESS"
     *    }
     *
     * @apiError InternalServerError.
     *
     * @apiErrorExample Error-Response:
     *     HTTP/1.1 500 Internal Server Error
     *  {
     *      "timestamp":1504064947603,
     *      "status":500,
     *      "error":"Internal Server Error",
     *      "exception":"java.lang.ArithmeticException",
     *      "message":"/ by zero",
     *      "path":"/api/wap/collection/{id}"
     *  }
     */
    @RequestMapping(value = "/api/wap/collection/{id}", method = RequestMethod.GET)
    public String findCommentId(@PathVariable("id")Long  id) {
        MsgOut o = MsgOut.success(collectionService.selectByPK(id));
        return this.renderJson(o);
    }

    /**
     * 店铺的关注个数
     * @param collection
     * @param userId
     * @return
     */
    @RequestMapping(value = "/api/wap/collection/companyCount", method = RequestMethod.GET)
    public String companyCount(Collection collection,@RequestHeader(value="headId",required = false) String userId) {
        if (ObjectUtils.isEmpty(userId)) {
            return this.renderJson(MsgOut.error("Plz login."));
        }
        MsgOut o = MsgOut.success(collectionService.companyCount(collection));
        return this.renderJson(o);
    }

}
